package com.informationsystem.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.informationsystem.service.DownloadsManager;
import com.informationsystem.service.SystemuserManager;
import com.informationsystem.service.TagManager;
import com.informationsystem.dao.SearchException;
import com.informationsystem.model.Downloads;
import com.informationsystem.model.Tag;
import com.informationsystem.webapp.action.BaseAction;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

public class DownloadsAction extends BaseAction implements Preparable {
    private DownloadsManager downloadsManager;
	private TagManager tagManager;
    private List downloadss;
    private Downloads downloads;
    private Long id;
    private String query;
    private Date hourformat;
    private Tag tag;
    private File downloadsfile;
    private String contentType;
    private String filename;

    public void setDownloadsManager(DownloadsManager downloadsManager) {
        this.downloadsManager = downloadsManager;
    }

    public List getDownloadss() {
        return downloadss;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String downloadsId = getRequest().getParameter("downloads.id");
            if (downloadsId != null && !downloadsId.equals("")) {
                downloads = downloadsManager.get(new Long(downloadsId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            downloadss = downloadsManager.search(query, Downloads.class);
        } catch (SearchException se) {
            addActionError(se.getMessage());
            downloadss = downloadsManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Downloads getDownloads() {
        return downloads;
    }

    public void setDownloads(Downloads downloads) {
        this.downloads = downloads;
    }

    public String delete() {
    	downloads = downloadsManager.get(downloads.getId());
    	File file = new File(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+
    								"downloads_"+downloads.getId() + "_" + downloads.getFilename());
    	file.delete();
        downloadsManager.remove(downloads.getId());
        addLog("delete downloads id:" +downloads.getId() + " title: "+ downloads.getTitle());
        saveMessage(getText("downloads.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            downloads = downloadsManager.get(id);
        } else {
            downloads = new Downloads();
            downloads.setSystemuser(getLoginUser());
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (downloads.getId() == null);
        
        if(isNew)
        	downloads.setFilename(filename);

        if(isNew)
        	downloads.setPostDate(generatePostDate());
        else
        	downloads.setPostDate(new Date());
        downloads = downloadsManager.save(downloads);
        
        if(isNew){
        	saveFile("downloads_"+downloads.getId() + "_" + filename, downloadsfile);
        }

        String key = (isNew) ? "downloads.added" : "downloads.updated";
        saveMessage(getText(key));
        
        if(!isNew){
        	addLog("edit downloads id:" +downloads.getId() + " title: "+ downloads.getTitle());
        }
        else{
        	addLog("add downloads id:" +downloads.getId() + " title: "+ downloads.getTitle());
        }
        
        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }

    public void saveFile(String tosavefilename, File tosavefile) throws IOException{
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		File f = new File(path);
        if(!f.exists()){
            f.mkdir(); 
        }     
        FileOutputStream fos = new FileOutputStream(ServletActionContext.getServletContext().getRealPath("/upload")+"\\"+tosavefilename);
        InputStream is = new FileInputStream(tosavefile);
        byte[] buffer = new byte[8192];
        int count = 0;
        while ((count = is.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
    	}
        fos.flush();
    	fos.close();
    	is.close();
    }
    
	public SystemuserManager getSystemuserManager() {
		return systemuserManager;
	}

	public void setSystemuserManager(SystemuserManager systemuserManager) {
		this.systemuserManager = systemuserManager;
	}

	public TagManager getTagManager() {
		return tagManager;
	}

	public void setTagManager(TagManager tagManager) {
		this.tagManager = tagManager;
	}
	
	public List getTagList(){
		return tagManager.getAll();
	}
	
	public List getSystemuserList(){
		return systemuserManager.getAll();
	}
	
	public Date getHourformat() {
		return downloads.getPostDate();
	}

	public void setHourformat(Date hourformat) {
		this.hourformat = hourformat;
	}
	
	@SuppressWarnings("deprecation")
	public Date generatePostDate(){
		Calendar cal = Calendar.getInstance();
		cal.setTime(downloads.getPostDate()); 
		cal.set(Calendar.HOUR_OF_DAY, hourformat.getHours());
		cal.set(Calendar.MINUTE,hourformat.getMinutes());

		return cal.getTime();
	}
	
	public String deleteDownloadsTag(){
 	   downloads = downloadsManager.get(downloads.getId());
  	   downloads.getTags().remove(tagManager.get(getTag().getId()));
	   downloadsManager.save(downloads);
	    return SUCCESS;
	}
	
    public String addDownloadsTag() throws Exception{
	 	 downloads = downloadsManager.get(downloads.getId());
	  	 downloads.getTags().add(tagManager.get(getTag().getId()));
	     downloadsManager.save(downloads);
	     return SUCCESS;
     }

	public Tag getTag() {
		return tag;
	}

	public void setTag(Tag tag) {
		this.tag = tag;
	}

	public File getDownloadsfile() {
		return downloadsfile;
	}

	public void setDownloadsfile(File downloadsfile) {
		this.downloadsfile = downloadsfile;
	}
	
    public void setDownloadsfileContentType(String contentType) {
        this.contentType = contentType;
     }

     public void setDownloadsfileFileName(String filename) {
        this.filename = filename;
     }
}